using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using EventLogger.DataLayer;
using System.Configuration;

namespace EventLogger.Web.Controllers
{
    public class BrowseController : Controller
    {
        private int pageSize
        {
            get
            {
                return Int32.Parse(ConfigurationManager.AppSettings["pageSize"]);
            }
        }

        private EventLoggerEntities entites = new EventLoggerEntities();

        //
        // GET: /Event/

        public ActionResult Event(int eventId, int? page)
        {            
            var curPage = page ?? 1;
            
            var events = entites.Events.Where(e => e.Event.Id == eventId).OrderByDescending(e => e.TimeRaised);

            ViewData.Model = MakePages(events, page);

            ViewData["event"] = entites.EventDefinitions.Where(e => e.Id == eventId).FirstOrDefault().Name;

            return View();
        }

        public new ActionResult User(string userName, int? page)
        {            
            var curPage = page ?? 1;            

            IQueryable<EventEntity> events;

            events = entites.Events;

            if (userName == null)
            {
                events = events.Where(e => string.IsNullOrEmpty(e.UserName));
            }
            else
            {
                events = events.Where(e => e.UserName == userName);
            }

            events = events.OrderByDescending(e => e.TimeRaised); 

            ViewData.Model = MakePages(events, page);

            ViewData["user"] = string.IsNullOrEmpty(userName) ? "(empty)" : userName;

            return View();
        }

        public ActionResult Computer(string computerName, int? page)
        {
            var curPage = page ?? 1;            

            var events = entites.Events.Where(e => e.MachineName == computerName).OrderByDescending(e => e.TimeRaised);

            ViewData.Model = MakePages(events, page);

            ViewData["computer"] = computerName;

            return View();
        }

        private IQueryable<EventEntity> MakePages(IQueryable<EventEntity> entries, int? currentPage)
        {
            ViewData["totalPages"] = (int)Math.Ceiling((decimal)entries.Count() / pageSize);
            

            currentPage = currentPage ?? 1;

            ViewData["currentPage"] = currentPage;

            return entries.Skip((currentPage.Value - 1) * pageSize).Take(pageSize);
        }

    }
}
